package com.sxt.service.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import com.sxt.entity.Account;
import com.sxt.service.AccountOperate;

/**
 * 账户操作实现类
 * @author lovemanai
 *
 */
public class AccountOperateImpl implements AccountOperate {
	
	
	
	/*
	 * 存款
	 */
	@Override
	public void despoit(Account account, double money, Connection conn) {
		account.setMoney(account.getMoney() + money);
		updateMoney(account, conn);
	}

	/*
	 *	取款
	 */
	@Override
	public void withdraw(Account account, double money, Connection conn) {
		if(money > 3000) {
			System.out.println("单次取款金额不得超过3000！");
		} else if(money > account.getMoney()) {
			System.out.println("余额不足！");
		} else {
			account.setMoney(account.getMoney() - money);
			updateMoney(account, conn);
		}
		
	}

	/*
	 *	转账
	 *	转账收取百分之一的手续费
	 *	不可以转账给自己
	 */
	@Override
	public void tranfs(Account outAccount, Account inAccount, double money, Connection conn) {
		if(money * 1.0001 > outAccount.getMoney()) {
			System.out.println("余额不足！");
		} else if(outAccount.getAccountNo().equals(inAccount.getAccountNo())) {
			System.out.println("不可以转账给自己！");
		} else {
			outAccount.setMoney(outAccount.getMoney() - money * 1.001);
			updateMoney(outAccount, conn);
			inAccount.setMoney(inAccount.getMoney() + money);
			updateMoney(inAccount ,conn);
		}
		
	}

	/*
	 * 查询账户
	 */
	@Override
	public void search(Account account) {
		System.out.println(account);
		
	}
	
	public void updateMoney(Account account, Connection conn) {
		Statement sta = null;
		try {
			sta = conn.createStatement();
			String sql = "update account set money = " + account.getMoney() + "where accountNo = " + "'" + account.getAccountNo() + "'";
			sta.execute(sql);
		} catch(SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if(sta != null) {
					sta.close();
					sta = null;
				}
			} catch(SQLException e) {
				e.printStackTrace();
			}
			
		}
	}

}
